package ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.historyRFC;

import java.sql.ResultSet;
import java.util.ArrayList;

import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.HistoryMaker;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.controller.database.DatabaseConnection;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.model.History;
import ch.bfh.abhmcm.SoftwareEngineeringAndDesign.view.mainframe.historyRFCPanel.HistoryRFCPanel;

public class LoadspecHistoryThread extends Thread {

	private HistoryRFCPanel historyRFCPanel;
	private DatabaseConnection connection;

	public LoadspecHistoryThread(HistoryRFCPanel historyRFCPanel) {

		this.historyRFCPanel = historyRFCPanel;
	}

	@Override
	public void run() {
		this.connection = new DatabaseConnection();
		historyRFCPanel.getHistoryRFCFunctionPanel().getProgress()
				.setVisible(true);

		historyRFCPanel.getHistoryRFCListPanel().getHistoryTable()
				.setVisible(false);
		connection.connect();

		String query = "SELECT * FROM cms_history WHERE "
				+ History.TC_SOURCE
				+ " = '"
				+ historyRFCPanel.getHistoryRFCFunctionPanel().getSerchfield()
						.getText() + "'";
		ResultSet rs = connection.query(query);

		historyRFCPanel.getHistoryRFCListPanel().getHistoryTable().clearTable();

		ArrayList<History> historyList = new ArrayList<History>();
		int count = 0;
		
		try {
			while (rs.next()) {
				HistoryMaker maker = new HistoryMaker();
				historyList.add(maker.createHistoryEntry(rs));
				count++;
			}
		} catch (Exception e) {
		}

		if (count == 0) {

			this.historyRFCPanel.getHistoryRFCListPanel().getHistoryTable()
			.setVisible(false);
			this.historyRFCPanel.getHistoryRFCListPanel().getHistoryTable()
					.displayNoEntry();
			this.historyRFCPanel.getHistoryRFCListPanel().getHistoryTable()
			.setVisible(true);
		} else {

			this.historyRFCPanel.getHistoryRFCListPanel().getHistoryTable()
					.setVisible(false);
			for (History history : historyList) {
				this.historyRFCPanel.getHistoryRFCListPanel().getHistoryTable()
						.addEntryToTable(history);
			}
			this.historyRFCPanel.getHistoryRFCListPanel().getHistoryTable()
					.setVisible(true);
		}
		
		historyRFCPanel.getHistoryRFCFunctionPanel().getSerchfield()
				.setText("");
		historyRFCPanel.getHistoryRFCFunctionPanel().getLoadSpecRFCHistory().setText("History von RFC ... laden");
		historyRFCPanel.getHistoryRFCFunctionPanel().getProgress()
				.setVisible(false);
		connection.disconnect();
	}

}
